﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SyringeControl.ControlSamples
{
    /// <summary>
    /// 
    /// </summary>
    /// <remarks>This control requires a spellchecker passed into its constructor, so its instances can't be built using Activator</remarks>
    class SpellCheckingTextBox : TextBox
    {
        ISpellChecker _spellChecker;
        public SpellCheckingTextBox(ISpellChecker spellChecker)
        {
            _spellChecker = spellChecker;
        }

        public event EventHandler<SpellingEventArgs> IncorrectSpelling;

        void InvokeIncorrectSpelling(string text, bool isCorrect)
        {
            var handler = IncorrectSpelling;
            if (handler != null)
            {
                handler(this, new SpellingEventArgs { Text = text, IsCorrect = isCorrect });
            }
        }
        bool wasCorrectLastTime;
        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);
            var isCorrect = _spellChecker.IsCorrect(this.Text);
            if (isCorrect != wasCorrectLastTime)
                InvokeIncorrectSpelling(Text, isCorrect);
            wasCorrectLastTime = isCorrect;
        }
    }
    class SpellingEventArgs: EventArgs
    {
        public string Text {get;set;}
        public bool IsCorrect{get;set;}
    }

    interface ISpellChecker
    {
        bool IsCorrect(string s);
    }

    class DictionarySpellChecker : ISpellChecker
    {
        ILookup<char, string> _words;
        public DictionarySpellChecker(IEnumerable<string> words)
        {
            _words = words.Where(word => String.IsNullOrEmpty(word)).ToLookup(word => word[0]);
        }

        public bool IsCorrect(string s)
        {
            if(String.IsNullOrEmpty(s))
                return true;
            return (from cluster in _words
                   where cluster.Key == s[0]
                   select cluster.Any(word => word.StartsWith(s))).Any();
        }
    }
}
